<!--
 @description 其他筛选条件
 @fileName OtherFilterWindow.vue
 @author zengqiongying
 @created 2023/01/05 09:52:56
-->
<template>
  <Popup v-model="popShow" :title="filterFlag==='sort'?'排序':'筛选'" :show-confirm-button="false" :show-cancel-button="false" position="bottom">
    <div class="other-filter-box" @scroll.stop @touchmove.stop>
      <Scroll vertical class="scroll-height" @click.native.stop>
        <div class="filter-content">
          <Card :show-btns="filterFlag!=='sort'" @reset="resetHandle" @confirm="confirmHandle">
            <template v-for="(f,i) in filtersView">
              <template v-if="filterFlag==='filter'">
                <div :key="i" class="filter-content-title" row>
                  <span>{{ f.title }}</span>
                  <div @click.stop="foldClickHandle(f)">
                    <span>{{ isFold(f)?'更多':'收起' }}</span>
                    <svg-icon :icon-class="isFold(f)?'xiangxia-zhankai-line':'xiangshang-shouqi-line'" />
                  </div>
                </div>
                <template v-if="!isFold(f)">
                  <template v-if="f.type=='daterange'">
                    <div :key="f.flag + i" class="filter-content-field" row>
                      <van-field v-model="f.value1" class="cus-field" label="" left-icon="calendar-o" readonly placeholder="选择日期" @click.native="openCaledar(f)" />
                      <div class="separator" />
                      <van-field v-model="f.value2" class="cus-field" label="" left-icon="calendar-o" readonly placeholder="选择日期" @click.native="openCaledar(f)" />
                    </div>
                  </template>
                  <template v-if="f.type=='monthrange'">
                    <div :key="f.flag + i" class="filter-content-field" row>
                      <FieldDateTime
                        v-model="f.value1"
                        type="year-month"
                        class="cus-field"
                        :min-date="caledarMinDate"
                        :max-date="caledarMaxDate"
                        @change="changeFieldValues(f,'value1')"
                      />
                      <div class="separator" />
                      <FieldDateTime
                        v-model="f.value2"
                        type="year-month"
                        class="cus-field"
                        :min-date="caledarMinDate"
                        :max-date="caledarMaxDate"
                        @change="changeFieldValues(f,'value2')"
                      />
                    </div>
                  </template>
                  <template v-if="f.type==='textrange'">
                    <div :key="f.flag + i" class="filter-content-field" row>
                      <van-field
                        v-model="f.value1"
                        :type="f.fieldType || 'text'"
                        class="cus-field"
                        label=""
                        :placeholder="f.placeholder1"
                        clearable
                        format-trigger="onBlur"
                        :formatter="f.formatter || null"
                      />
                      <div class="separator" />
                      <van-field
                        v-model="f.value2"
                        :type="f.fieldType || 'text'"
                        class="cus-field"
                        label=""
                        :placeholder="f.placeholder2"
                        clearable
                        format-trigger="onBlur"
                        :formatter="f.formatter || null"
                      />
                    </div>
                  </template>
                  <template v-else>
                    <div v-for="(c,m) in f.children || []" :key="c.value + m" :class="['filter-content-item',{'filter-content-item-selected':c.selected}]" @click.stop="selectedClick(c, f)">
                      <span class="filter-content-text">{{ c.label }}</span>
                      <img v-show="c.selected" class="filter-content-img" :src="sectionImg">
                    </div>
                  </template>
                </template>
              </template>
              <template v-else-if="filterFlag==='sort'">
                <div v-for="(c,m) in f.children || []" :key="m" row :class="['sort-content-text',{'selected':c.selected}]" @click.stop="selectedClick(c, f)">
                  <span>{{ c.label }}</span>
                  <img v-show="c.selected" class="filter-content-selected" src="~@/assets/icon-yes.png">
                </div>
              </template>
            </template>
          </Card>
        </div>
      </Scroll>
    </div>

    <van-calendar
      v-if="showCaladar"
      v-model="caledar.show"
      type="range"
      color="#05C4C3"
      :title="caledar.title"
      :min-date="caledarMinDate"
      :max-date="caledarMaxDate"
      :default-date="caledar.defaultData"
      :style="{'height':'500px'}"
      allow-same-day
      @confirm="onConfirmCaledar"
    />
  </Popup>
</template>

<script>
import Popup from '@/components/Popup'
import FieldDateTime from '@/components/FieldDateTime'
import Scroll from '@/components/Scroll'
import Card from '@/components/NavFilter/Card'
import sectionImg from '@/assets/selection@2x.png'
import selectedImg from '@/assets/icon-yes.png'
import { mapGetters, mapMutations } from 'vuex'
import mixins from '@/components/NavFilter/otherMixins'
export default {
  name: 'OtherFilterWindow',
  components: { Popup, Scroll, Card, FieldDateTime },
  mixins: [mixins],
  props: {
    visiable: {
      type: Boolean,
      default: false
    },
    filterFlag: {
      // 筛选类型：filter/sort
      type: String,
      default: 'filter'
    }
  },
  data() {
    return {
      sectionImg,
      selectedImg,
      // 临时记录本次选择，如果不点确定则关闭弹窗时清楚
      tempFiltersValue: [],
      caledarMinDate: '',
      caledarMaxDate: '',
      caledar: {
        show: false,
        field: '', // 当前字段
        defaultData: []
      }
    }
  },

  computed: {
    ...mapGetters('nav', ['filterData']),
    popShow: {
      set(val) {
        this.$emit('update:visiable', val)
      },
      get(val) {
        return this.visiable
      }
    },
    filtersView() {
      let result
      if (this.filterFlag === 'filter') {
        result = this.filterData.filter(v => v.flag !== 'sort')
      } else if (this.filterFlag === 'sort') {
        // 排序
        result = this.filterData.filter(v => v.flag === 'sort')
      } else {
        result = []
      }
      // 商品中心特殊处理
      result = result.filter(e => {
        return e.relevanceItemShow === undefined || e.relevanceItemShow
      })
      return result
    },
    showCaladar() {
      return this.filterData.some(v => v.type === 'daterange')
    }
  },
  watch: {
    popShow(v) {
      this.limitScroll()
    },
    '$route': {
      handler() {
        this.updateFilterData([])
        this.popShow = false
      },
      immediate: true
    }
  },
  mounted() {
  },
  beforeDestroy() {

  },
  created() {
  },
  methods: {
    ...mapMutations('nav', ['updateFilterData']),
    // 去掉所有
    cancelSelectedAll(list, type) {
      for (const item of list) {
        delete item.fold // 重置折叠收起
        if (type !== 'switch' && item.selected) {
          this.tempFiltersValue.push({
            filter: item,
            rawValue: item.selected,
            value: false
          })
        }
        this.$set(item, 'selected', false)
        const children = item.children || item.next
        if (children instanceof Array) {
          this.cancelSelectedAll(children, type)
        }
      }
    },

    // 展开收起
    foldClickHandle(f) {
      if (f.fold) {
        this.$set(f, 'fold', false)
      } else {
        this.$set(f, 'fold', true)
      }
    },
    // 是否折叠
    isFold(f) {
      if (f.fold === undefined) {
        if (f.isDefaultFolded === 1 || f.isDefaultFolded === '1') {
          // 如果fold不存在且isDefaultFolded等于1则设置fold值，解决单击更多，收起的bug
          this.$set(f, 'fold', true)
          return true
        }
        return false
      }
      return f.fold
    },
    // 选中
    selectedClick(f, obj) {
      let multiple = true
      let list = []
      if (this.filterFlag === 'filter') {
        multiple = !!obj.multiple
        list = obj.children
      } else if (this.filterFlag === 'sort') {
        multiple = false
        list = obj.children
      }
      let rawSelected = f.selected
      if (!multiple && this.$isType(list, 'Array')) {
        this.cancelSelectedAll(list)
      }
      if (this.filterFlag === 'sort') {
        rawSelected = false
      }

      if (rawSelected) {
        this.$set(f, 'selected', false)
        this.tempFiltersValue.push({
          filter: f,
          rawValue: true,
          value: false
        })
      } else {
        this.$set(f, 'selected', true)
        this.tempFiltersValue.push({
          filter: f,
          rawValue: false,
          value: true
        })
      }

      // 商品中心特殊处理
      if (obj.relevanceItemIndex && obj.relevanceItemIndex.length > 0) {
        obj.relevanceItemIndex.forEach(index => {
          const selected = obj.children.some(e => e.selected)
          this.$store.commit('nav/updateRelevanceItemShow', { index, selected })
          if (!selected) {
            this.cancelSelectedAll(this.filterData[index].children || [])
          }
        })
      }

      this.$nextTick(() => {
        this.$emit('refresh')
        if (obj && obj.flag === 'sort') {
          this.popShow = false
        }
      })
    },
    // 重置选择
    resetHandle() {
      if (this.filterFlag === 'filter') {
        this.cancelSelectedAll(this.filtersView)
        this.filtersView.forEach(item => {
          if (['textrange', 'daterange', 'monthrange'].includes(item.type)) {
            this.$set(item, 'value1', '')
            this.$set(item, 'value2', '')
          } else if (item.type === 'text') {
            this.$set(item, 'value', '')
          }
        })
      }
      this.tempFiltersValue = []
    },
    // 还原选中
    recoverSelected() {
      for (const t of this.tempFiltersValue) {
        this.$set(t.filter, 'selected', t.rawValue)
      }
      this.filtersView.forEach(item => {
        if (['textrange', 'daterange', 'monthrange'].includes(item.type)) {
          this.$set(item, 'value1', item.rawValue1 || '')
          this.$set(item, 'value2', item.rawValue2 || '')
        } else if (item.type === 'text') {
          this.$set(item, 'value', item.rawValue || '')
        }
      })
      this.tempFiltersValue = []
    },
    // 确定筛选
    confirmHandle() {
      this.tempFiltersValue = []
      this.filterData.forEach(v => {
        if (['textrange', 'daterange', 'monthrange'].includes(v.type)) {
          this.$set(v, 'rawValue1', v.value1 || '')
          this.$set(v, 'rawValue2', v.value2 || '')
        }
      })
      // 调用
      this.$nextTick(() => {
        this.$emit('refresh')
        this.popShow = false
      })
    },
    // 限制滚动
    limitScroll() {
      if (this.popShow) {
        document.body.classList.add('limit-scroll')
      } else {
        document.body.classList.remove('limit-scroll')
      }
    }
  }
}

</script>
<style lang='less' scoped>
.other-filter-box{
  --height:80vh;
  margin: 0 -16px;
  // height: var(--height);
  position: relative;
  /deep/ .scroll-height{
    max-height:var(--height);
  }
  .filter-content{
    min-height: 100px;
    background-color: #fff;
    .filter-content-item{
      position: relative;
      height: 100%;
      width: 100%;
      text-align: center;
      box-sizing: border-box;
      background-color: #F3F4F5;
      overflow: hidden;
      .filter-content-text{
        flex: 0 0 auto;
        // width: 100%;
        font-size: 12px;
        color: #333;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        display: block;
        padding: 0 4px;
      }
      .filter-content-img{
        position: absolute;
        bottom: 0;
        right: 0;
        width: 16px;
        height: 16px;
      }
    }
    .filter-content-item-selected{
      border: 1px solid #16BC83;
      border-radius: 2px;
    }
    // 展开收起
    .filter-content-title{
      display: flex;
      justify-content: space-between;
      align-items: center;
      &>div{
        color: #888;
        font-size: 12px;
        &>svg{
          color: inherit;
          font-size: inherit;
          margin-left: 2px;
        }
      }
    }

  .filter-content-field{
      padding: 0  0 0 10px !important;
      width: 100%;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: space-between;
      &.row{
        margin-top: 16px;
      }
      .cus-field{
        flex: 1;
        height: 36px;
        line-height: 1;
        background: rgba(241, 241, 242, .5);
        /deep/ .van-cell{
          background: rgba(241, 241, 242, .5);
          ::after{
            display: none;
          }
        }
      }
      .separator{
        margin: 0 16px;
        width: 23px;
        height: 2px;
        background: #B5B7C4;
        border-radius: 1px;
      }
    }

    .sort-content-text{
      width: 100%;
      display: flex;
      align-items: center;
      justify-content:space-between;
      line-height: 22px;
      padding: 10px 0;
      margin: 0 !important;
      border-bottom:1px solid rgba(241, 241, 242, .5);
      &.selected{
        color: #00C8B4 !important;
      }
      .filter-content-selected{
        width: auto;
        height: 14px;
      }
    }

    /deep/ .card-content{
      // min-height: calc(var(--height) - 72px);
      min-height: 200px;
      box-sizing: border-box;
      &>div:first-child{
        margin-top: 0 !important;
      }
    }
  }
}
</style>

